package analyticsServer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Pattern;
import managementClient.IClientRMI;

/**
 *
 * @author Group 95
 */
public class AnalyticsClient
{
    private final IClientRMI client;
    private String clientId;
    //        private final String clientId;
    private final ArrayList<String> arSubscriptions;
    private final CopyOnWriteArrayList<Pattern> arPatterns; //iterator uses a copy if the list gets changed during iterator usage

    public AnalyticsClient(final IClientRMI client,final String clientId,final String subscriptionId,final String regex)
    {
        this.clientId=clientId;
        this.client=client;
        arSubscriptions=new ArrayList<String>();
        arPatterns=new CopyOnWriteArrayList<Pattern>();
        this.arSubscriptions.add(subscriptionId);
        this.arPatterns.add(Pattern.compile(regex));
    }

    public void addSubscription(final String subscriptionId,final String regex)
    {
        synchronized(this)
        {
            this.arSubscriptions.add(subscriptionId);
            this.arPatterns.add(Pattern.compile(regex));
        }
    }

    public synchronized boolean deleteSubscription(final String subscriptionId)
    {
        boolean bRet=false;
        for(int i=0;i<this.arSubscriptions.size();i++)
        {
            if(this.arSubscriptions.get(i).equals(subscriptionId))
            {
                this.arPatterns.remove(i);
                this.arSubscriptions.remove(i);
                bRet=true;
                break;
            }
        }
        return bRet;
    }

    /**
    * Returns the Patterns of this Client.
    * @return Pattern[]
    */
    public Iterator<Pattern> iterator()
    {
        return this.arPatterns.iterator();
    }
    
    /**
     * Returns <tt>true</tt> if this Client has no Subscriptions.
     *
     * @return <tt>true</tt> if this client has no Subscriptions
     */
    public boolean hasNoSubscriptions()
    {
        return this.arSubscriptions.isEmpty();
    }
    
    /**
     * Returns the unique Id of the Client
     * @return 
     */
    public String getId()
    {
        return clientId;
    }
    
    /**
     * Returns the RMI-Client-Object
     * @return 
     */
    public IClientRMI getRMIClient()
    {
        return this.client;
    }    
}
